import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Input, PageContainer, Picker, Switch, View } from "@tarojs/components";
import { useReactive } from "ahooks";
import { pick, omit } from "lodash-es";
import dayjs from "dayjs";

import ByText from "@/components/ui/ByText";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import ByIcon from "@/components/ui/ByIcon";
import Page from "@/components/common/Page";
import ByButton from "@/components/ui/ByButton";
import PopupMember from "@/components/app/PopupMember";
import ByImageGroup from "@/components/ui/ByImageGroup";
import usePageEventChannel from "@/hooks/usePageEventChannel";

import useForm from "@/hooks/useForm";
import ApiInspection from "@/api/inspection";
import { pickTransMap } from "@/utils";

const CellProps = {
  labelWidth: "7em",
  border: true,
} as const;

const TaskItems = ({
  index,
  source,
  onPicker,
}: {
  index: number;
  source: any;
  onPicker: () => void;
}) => {
  const model = useReactive(source);

  return (
    <View className="p-3">
      <ByCell size="small" label={`第${index + 1}项 ${source.quesName}`} />
      <Card>
        <ByCell label="备注" {...CellProps} border={false}>
          <ByText type="second">{source.quesRemark}</ByText>
        </ByCell>

        <ByCell label="问题图片" {...CellProps}>
          <ByImageGroup
            urls={source.picList}
            size={50}
            limit={3}
            showEmptyTip
          />
        </ByCell>

        <ByCell label="整改" {...CellProps}>
          <Switch
            checked={model.flag}
            onChange={({ detail }) => (model.flag = detail.value)}
          />
        </ByCell>

        {model.flag && (
          <>
            <ByCell
              {...CellProps}
              requierd
              label="整改责任人"
              nextIcon={<ByIcon name="PlusCirlce" size={32} />}
              onClick={onPicker}
            >
              <Input
                disabled
                value={source.supplyName || source.headerName}
                placeholder="请选择整改责任人"
                className="w-full"
              />
            </ByCell>

            <Picker
              mode="date"
              start={dayjs().format("YYYY-MM-DD")}
              value={source.requaireProcessDate}
              onChange={({ detail }) =>
                (model.requaireProcessDate = detail.value)
              }
            >
              <ByCell
                {...CellProps}
                requierd
                label="整改时间"
                nextIcon={<ByIcon name="Calendar" size={32} />}
              >
                <Input
                  disabled
                  placeholder="选择要求整改时间"
                  value={model.requaireProcessDate}
                />
              </ByCell>
            </Picker>
          </>
        )}
      </Card>
    </View>
  );
};

const omitKeys = ["options", "picList"];
const rules = {
  rectificationData: {
    type: "array",
    required: true,
    message: "请设置整改项",

    defaultField: {
      type: "object",
      validator(rules, value, callback) {
        const index = +rules.field + 1;

        if (!(value.headerId || value.supplyId)) {
          callback(new Error(`第${index}项 未填写整改责任人`));
        } else if (!value.requaireProcessDate) {
          callback(new Error(`第${index}项 未填写整改时间`));
        } else {
          callback();
        }
      },
    },
  },
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [list, setList] = useState<any>();

  usePageEventChannel("acceptRectificationList", (data) => {
    setList(data);
  });

  const { loading, setModel } = useForm(ApiInspection.inspectionRectification, {
    submitOnUpdate: true,
    // @ts-expect-error
    rules,
    onSuccess() {
      Taro.showToast({ title: "提交成功！" });
      setTimeout(() => {
        Taro.navigateBack({ delta: 1 });
      }, 1500);
    },
  });

  const [index, setIndex] = useState(-1);

  // 确认整改责任人
  const handleConfirm = (data, type) => {
    const defaultObj = {
      // billType
      headerId: undefined,
      headerName: "",

      supplyId: undefined,
      supplyCode: "",
      supplyName: "",
    };

    const isSup = type == "supplier";

    const obj = isSup
      ? pick(data, ["supplyCode", "supplyName", "supplyId"])
      : pickTransMap(data, { userId: "headerId", userName: "headerName" });

    Object.assign(list[index], { ...defaultObj, ...obj });
    setIndex(-1);
  };

  const handleSubmit = () => {
    setModel({
      intentCustomerId,
      rectificationData: list
        .filter((e) => e.flag)
        .map((e) => ({
          ...omit(e, omitKeys),
          quesID: e.quesId,
          intentCustomerId,
          requaireProcessDate: e.requaireProcessDate || "",
        })),
    });
  };

  return (
    list && (
      <>
        <Page
          footerSticky
          slotFooter={
            <ByButton size="large" loading={loading} onClick={handleSubmit}>
              提交
            </ByButton>
          }
        >
          <View className="bg-warning p-3">
            巡检不合格项,共{list?.length || 0}项
          </View>

          {list.map((item, index) => (
            <TaskItems
              source={item}
              key={item.id}
              index={index}
              onPicker={() => setIndex(index)}
            />
          ))}
        </Page>

        <PageContainer show={index > -1} onAfterLeave={() => setIndex(-1)}>
          <PopupMember
            title="整改责任人"
            intentCustomerId={intentCustomerId}
            type={["project", "supplier"]}
            onCancel={() => setIndex(-1)}
            onConfirm={handleConfirm}
          />
        </PageContainer>
      </>
    )
  );
};
